/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tmanager;

/**
 *
 * @author matteomaiero
 */
import java.util.Properties;
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EMailManager {

    @Resource(name = "Email")
    private Session mailSession;

    /**
     * Metodo per l'invio di email
     * @param recipient String rappresentante l'email del cliente al quale deve essere inviata eMail
     * @param subject String che rappresenta l'oggetto dell'eMail
     * @param text String che rappresenta il testo dell'email
     * @return True se l'email è inviata correttamente
     */
    public boolean inviaEMail(String recipient, String subject, String text) {
        boolean exe = false;
        Properties p = new Properties();
        InitialContext c = null;
        try {
            c = new InitialContext();
            mailSession = (javax.mail.Session) c.lookup("java:comp/env/Email");
        } catch (NamingException ne) {
            ne.printStackTrace(); //inserire log
        }
        String username = "k4h1ros@gmail.com";
        String password = "soriak2010";
        Transport transport = null;
        try {
            Message msg = new MimeMessage(mailSession);
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
            msg.setSubject(subject);
            msg.setText(text);
            msg.saveChanges();
            transport = mailSession.getTransport("smtps");
            transport.connect(username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            exe = true;
        } catch (AddressException e) {
            e.printStackTrace();
            exe = false;
        } catch (MessagingException e) {
            e.printStackTrace();
            exe = false;
        } finally {
            try {
                if (transport != null) {
                    transport.close();
                }
            } catch (MessagingException me) {
                me.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return exe;
    }
}
